/**
 * 产品分类列表
 * 文件命名格式：zmn.模块名称.表名称.功能.jas
 * @author duanzuocai
 * @since 2018/11/01
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate', 'laytpl'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var laytpl = layui.laytpl;

    table.init('zmn-table', {
        toolbar: "#zmn-table-tool",
        page: true,
        limit: json.pageSize,
        height: 'full-189'
    });
    laypage.render(zmnPage.laypageOptions(json));

    // 区域下拉框联动
    zmnPage.laySelectLinkage(form, "/common/area/listChilds.action", "provinceId", "cityId", "countryId");


    // 移除/新增
    table.on("toolbar(zmn-table)", function (obj) {
        var ids = zmnPage.layTabldIds(obj, "serviceAreaId");
        if(obj.event == "remove") {
            if(ids.length === 0){ return layer.alert("请选择至少一条数据！"); }
            layer.confirm('确认移除区域吗？', function() {
                zmnPage.ajaxSimple("/channel/service/area/remove", { ids: ids.join(",")}, 1000);
            });
            return;
        }

        if(obj.event == "add") {
            showSelectArea(1);
        }

        if (obj.event == "batchSaveCategory") {
            if (ids.length === 0) {
                return layer.alert("请选择至少一条数据！");
            }

            zmnLayUtil.openTabsPageCustom(parent, "/channel/service/area/batchServiceCategory.action?serviceAreaIds="+ids.join(",")+'&channelId='+json.channelId+'&showType=2', "批量开通前台分类");
        }
    });

    function showSelectArea(areaId) {
        let areaMap;
        let url = "/area/listChilds.action?parentId=" + areaId;
        $.ajax({
            async: false,
            type: "GET", url: url,
            dataType: "json",
            success: function (data) {
                areaMap = data;
            },
            error: function (XMLHttpRequest, status, errorThrown) {
            }
        });

        let parentId = areaId == 1 ? 0 : areaMap.area.parentId;
        currLevel = areaId == 1 ? 0 : areaMap.area.level;
        if(areaMap.childs.length > 0){
            laytpl(selectAreaHtml.innerHTML).render({parentId: parentId, items: areaMap.childs}, function (html) {
                layer.close(childIndex);
                childIndex = layer.open({
                    type: 1,
                    title: '选择区域'
                    , content: html
                    , area: ['650px', '600px']
                });
            });
            table.init('zmn-select-area-table', {
                toolbar: "#zmn-select-area-table-tool",
                defaultToolbar: [],
                page: true,
                height: '500px'
            });

            $('.serachTable .layui-btn').on('click', function(){
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });

            var active = {
                reload: function(){
                    var firstLetter = $('#firstLetter').val().trim();
                    let childs = firstLetter == null || firstLetter == '' ? areaMap.childs : areaMap.childs.filter(p => p.firstLetter.toUpperCase() == firstLetter.toUpperCase());
                    //执行重载
                    table.reload('zmn-select-area-table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                        data: childs
                    });
                }
            };
        }else{
            layer.msg('下一级区域为空！');
        }
    }

    // 选择/返回上一级
    table.on("toolbar(zmn-select-area-table)", function (obj) {
        if (obj.event == "selectAll") {
            layer.confirm('确认添加全国城市吗？', function() {
                $.ajax({
                    type: "POST", url: "/channel/service/area/addAllCity",
                    dataType: "json", data: {channelId: json.channelId},
                    success: function (json) {
                        if(json.status == 200){
                            zmnPage.reload(json.message, 1000);
                        }else{
                            layer.alert(json.message);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                    }
                });
            });
        }
        if (obj.event == "select") {
            var ids = zmnPage.layTabldIds(obj, "areaId");
            if(ids.length === 0){ return layer.alert("请选择至少一条数据！"); }
            layer.confirm('确认添加区域吗？', function() {
                $.ajax({
                    type: "POST", url: "/channel/service/area/add",
                    dataType: "json", data: { ids: ids.join(","), channelId: json.channelId},
                    success: function (json) {
                        if(json.status == 200){
                            zmnPage.reload(json.message, 1000);
                        }else{
                            layer.alert(json.message);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                    }
                });
            });
        }
        if (obj.event == "parent") {
            let parentId = $('#parentId').val();
            if(parentId > 0){
                showSelectArea(parentId);
            }else{
                layer.msg('已到最上级!');
            }
        }
    })


    table.on('tool(zmn-select-area-table)', function (obj) {
        let areaId = obj.data.areaId;
        // 查看下一级
        if (obj.event === 'child') {
            showSelectArea(areaId);
        }
        // 选择
        if (obj.event === 'select') {
            layer.confirm('确认添加区域吗？', function() {
                $.ajax({
                    type: "POST", url: "/channel/service/area/add",
                    dataType: "json", data: { ids: areaId, channelId: json.channelId},
                    success: function (json) {
                        if(json.status == 200){
                            zmnPage.reload(json.message, 1000);
                        }else{
                            layer.alert(json.message);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                    }
                });
            });
        }

    });

    //对外暴露的接口
    exports('channel_service_area_list', {});
});


function drawMap(relateId) {
    layer.open({
        type: 2,
        title: '画地图',
        area: ['90%', '80%'],
        content: '/company/area/drawMap.action?relateId=' + relateId
    });
}

function reload(msg) {
    parent.layui.layer.msg(msg);
    window.location.reload();
}

